package com.example.main


import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.common.view.event.CustomEvent
import com.example.common.view.view.BaseMvvmActivity
import com.example.main.databinding.ActivityMainBinding
import com.example.main.databinding.ActivityMainTabBinding
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.badge.BadgeDrawable
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/main/MainActivity")
@AndroidEntryPoint
class MainActivity : BaseMvvmActivity<ActivityMainTabBinding>() {
    override fun getLayoutId(): Int =R.layout.activity_main_tab
    val title= arrayOf("首页","服务","消息","公告","我的")
    val nor_icons= intArrayOf(R.drawable.baseline_home_24,R.drawable.baseline_dehaze_24,
        R.drawable.baseline_chat_24, R.drawable.baseline_volume_down_24, R.drawable.baseline_person_24)
    val sel_icons= intArrayOf(R.drawable.baseline_home_25,R.drawable.baseline_dehaze_25,
        R.drawable.baseline_chat_25, R.drawable.baseline_volume_down_25,
        R.drawable.baseline_person_25)
    //定义需要哪些用户权限
    private val needUserPermission = arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION)
    //用户没有同意的权限
    private val unGrantPermission = arrayListOf<String>()
    private var hasUnGranted =false
    override fun initView() {
        super.initView()
        mDataBinding.vp.adapter=MyPageAdapter(this)
        val tabEntity=ArrayList<CustomTabEntity>()
        for(i in title.indices){
            tabEntity.add(SimpleTabEntity(title[i],sel_icons[i],nor_icons[i]))
        }
        mDataBinding.commonTab.setTabData(tabEntity)
        mDataBinding.commonTab.showMsg(3,5)
        mDataBinding.commonTab.setOnTabSelectListener(object:OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                mDataBinding.vp.currentItem=position
                if (position==3){
                    mDataBinding.commonTab.hideMsg(3)
                }
            }

            override fun onTabReselect(position: Int) {

            }

        })
        mDataBinding.vp.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mDataBinding.commonTab.currentTab=position

            }
        })
        //自定义发起权限授权
        mDataBinding.vp.postDelayed({
            autoRequestPermisstion()
        },3000)
    }

    /**
     * 处理其他业务发送的请求
     */
    override fun handEvent(event: CustomEvent) {
        super.handEvent(event)
        when(event.type){
            //有新消息
            100->{
                mDataBinding.commonTab.showMsg(2,event.data as Int)
            }
            //有新公告
            101->{
                mDataBinding.commonTab.showMsg(3,event.data as Int)
            }
        }
    }
    //使用RxPermission发起用户授权权限
    private fun autoRxPermisstion(){

    }
    private fun autoRequestPermisstion():Boolean{
        //判断系统版本,只有6.0以后才需要动态权限
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //清理一下未授权的用户权限
            unGrantPermission.clear()
            //查找还未授权的户权限
            needUserPermission.forEach {
                //检查当前权限是否被用户同意
                var permissionState = checkSelfPermission(it)
                if(permissionState==PackageManager.PERMISSION_DENIED){
                    unGrantPermission.add(it)
                }
            }
            //发起权限
            if(unGrantPermission.size>0){
                requestPermissions(unGrantPermission.toTypedArray(),102)
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode==102 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                //判断
                if (checkSelfPermission(it)==PackageManager.PERMISSION_DENIED){
                    hasUnGranted=true
                }
            }
        }
        //弹窗告诉用户去设置中心应用详情设置
        if(hasUnGranted){
            AlertDialog.Builder(this@MainActivity).apply {
                setTitle("权限提示")
                setMessage("没有授权,请到应用详情中设置")
                setPositiveButton("去设置"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted=false
                    openSettingAppDetail()
                }
                setNeutralButton("取消"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted=false
                }
            }.show()
        }
    }
    private fun openSettingAppDetail(){
        this@MainActivity.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package",packageName,null)))
    }

}